package cn.fl.spl.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrQueryApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.spl.service.ISplActivityRecService;
import cn.fl.spl.transform.SplActivityRecVOTransform;
import cn.fl.spl.vo.SplActivityRecVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.spl.api.ISplInfoApiService;
import fl.spl.facade.spl.api.ISplUsrRApiService;
import fl.spl.facade.spl.condition.SplActivityRecQC;
import fl.spl.facade.spl.condition.SplInfoQueryCondition;
import fl.spl.facade.spl.condition.SplUsrRQC;
import fl.spl.facade.spl.dto.SplActivityRecDTO;
import fl.spl.facade.spl.dto.SplInfoDTO;
import fl.spl.facade.spl.dto.SplUsrRDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 商家活动记录表 控制层
 */
@Controller
@RequestMapping("/spl/splActivityRec")
public class SplActivityRecController extends BaseController {

	/**
	 * SplActivityRec 服务层BEAN
	 */
	@Autowired
	private ISplActivityRecService splActivityRecService;
	@Autowired
	private ISysUsrQueryApiService sysUsrQueryApiService;
	@Autowired
	private ISplUsrRApiService splUsrRApiService;
	@Autowired
	private ISplInfoApiService splInfoApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {

		ModelAndView view = new ModelAndView("/spl/splActivityRec/splActivityRecList");
		
		Map<String, String> activiTypCdMap = new HashMap<String, String>();
		activiTypCdMap.put("WAL011", "新人注册");
		activiTypCdMap.put("WAL012", "企业准入");
		
		view.addObject("activityTypCdMap", activiTypCdMap);

		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("/splActivityRec/modify");
		view.addObject("id", id);
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String oldUsrMp = request.getParameter("oldUsrMp");
		String activityTypCd = request.getParameter("activityTypCd");
		String oldUsrSplNm = request.getParameter("oldUsrSplNm");
		String loginTmStar = request.getParameter("loginTmStar");
		String loginTmEnd = request.getParameter("loginTmEnd");
		String accessTmStar = request.getParameter("accessTmStar");
		String accessTmEnd = request.getParameter("accessTmEnd");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SplActivityRecQC qc = new SplActivityRecQC();
		if (StringUtils.isNotEmpty(oldUsrMp)) {
			SysUsrQueryCondition condition = new SysUsrQueryCondition();
			condition.setMpList(Arrays.asList(oldUsrMp));
			condition.setSysCd(SplSystemConstant.FL_SYS_CD);
			List<SysUsrDTO> searchUsrInfoList = this.sysUsrQueryApiService.searchUsrInfoList(condition);
			BaseLogUtils.newWebLogger("根据手机号查询,结果==>" + JSONObject.toJSONString(searchUsrInfoList))
					.setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();
			if (CollectionUtils.isNotEmpty(searchUsrInfoList)) {
				SysUsrDTO sysUsrDTO = searchUsrInfoList.get(0);
				qc.setRenewId(sysUsrDTO.getId());
			}
		}
		if (StringUtils.isNotEmpty(activityTypCd)) {
			qc.setActivityTypCd(activityTypCd);
		}
		if (StringUtils.isNotEmpty(oldUsrSplNm)) {
			SplUsrRQC usrRQC = new SplUsrRQC();
			usrRQC.setSplNm(oldUsrSplNm);
			List<SplUsrRDTO> splUsrRList = this.splUsrRApiService.searchSplUsrRList(usrRQC);
			if (CollectionUtils.isNotEmpty(splUsrRList)) {
				qc.setRenewId(splUsrRList.get(0).getUsrId());
			}
		}
		if (StringUtils.isNotEmpty(loginTmStar) && StringUtils.isNotEmpty(loginTmEnd)) {
			qc.setActivityTypCd("WAL011");
			qc.setStartTm(DateUtils.formatStringToDate(loginTmStar, DateUtils.YYYY_MM_DD));
			qc.setEndTm(DateUtils.formatStringToDate(loginTmEnd, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(accessTmStar) && StringUtils.isNotEmpty(accessTmEnd)) {
			qc.setActivityTypCd("WAL012");
			qc.setStartTm(DateUtils.formatStringToDate(accessTmStar, DateUtils.YYYY_MM_DD));
			qc.setEndTm(DateUtils.formatStringToDate(accessTmEnd, DateUtils.YYYY_MM_DD));
		}
		qc.setIsValid(BaseConstant.IS_YESNO_YES);
		page.setCondition(qc);

		Pager pager = this.splActivityRecService.searchListPage(page);
		
		List<SplActivityRecDTO> list = (List<SplActivityRecDTO>) pager.getResultList();
		List<JSONObject> resultList = new ArrayList<JSONObject>();
		if (CollectionUtils.isNotEmpty(list)) {
			List<Long> oldUsrIdList = new ArrayList<Long>();
			List<Long> newUsrIdList = new ArrayList<Long>();
			Map<Long, Integer> isAccessMap = new HashMap<Long, Integer>();
			Map<Long, Date> loginTmMap = new HashMap<Long, Date>();
			Map<Long, Date> accessTmMap = new HashMap<Long, Date>();
			
			List<SplActivityRecVO> voList = SplActivityRecVOTransform.toVOList(list);
			for (SplActivityRecVO splActivityRecVO : voList) {
				oldUsrIdList.add(splActivityRecVO.getRenewId());
				newUsrIdList.add(splActivityRecVO.getUsrId());
				if ( ! isAccessMap.containsKey(splActivityRecVO.getUsrId())) {
					isAccessMap.put(splActivityRecVO.getUsrId(), 0);
				}
				if (splActivityRecVO.getActivityTypCd().equals("WAL012")) {
					isAccessMap.put(splActivityRecVO.getUsrId(), 1);
					accessTmMap.put(splActivityRecVO.getUsrId(), splActivityRecVO.getCrtTm());
				}
				if (splActivityRecVO.getActivityTypCd().equals("WAL011")) {
					loginTmMap.put(splActivityRecVO.getUsrId(), splActivityRecVO.getCrtTm());
				}
			}
			
			// 查询用户信息
			SysUsrQueryCondition oldUsrCondition = new SysUsrQueryCondition();
			oldUsrCondition.setUsrIdList(oldUsrIdList);
			oldUsrCondition.setSysCd(CurrentThreadContext.getFlServiceSysCd());
			//oldUsrCondition.setIsValid(BaseConstant.IS_YESNO_YES);
			List<SysUsrDTO> oldUsrList = this.sysUsrQueryApiService.searchUsrInfoList(oldUsrCondition);
			Map<Long, SysUsrDTO> oldUsrMap = new HashMap<Long, SysUsrDTO>();
			for (SysUsrDTO sysUsrDTO : oldUsrList) {
				oldUsrMap.put(sysUsrDTO.getId(), sysUsrDTO);
			}
			SysUsrQueryCondition newUsrCondition = new SysUsrQueryCondition();
			newUsrCondition.setUsrIdList(newUsrIdList);
			newUsrCondition.setSysCd(CurrentThreadContext.getFlServiceSysCd());
			List<SysUsrDTO> newUsrList = this.sysUsrQueryApiService.searchUsrInfoList(newUsrCondition);
			Map<Long, SysUsrDTO> newUsrMap = new HashMap<Long, SysUsrDTO>();
			for (SysUsrDTO sysUsrDTO : newUsrList) {
				newUsrMap.put(sysUsrDTO.getId(), sysUsrDTO);
			}
			
			// 查询供应商
			SplUsrRQC usrRCondition = new SplUsrRQC();
			usrRCondition.setUsrIdList(oldUsrIdList);
			usrRCondition.setUsrTypCd("2");
			usrRCondition.setIsDel(BaseConstant.IS_YESNO_NO);
			List<SplUsrRDTO> splUsrRList = this.splUsrRApiService.searchSplUsrRList(usrRCondition);
			List<Long> splIdList = new ArrayList<Long>();
			Map<Long , Long> splUsrRMap = new HashMap<Long, Long>();
			for (SplUsrRDTO splUsrRDTO : splUsrRList) {
				splIdList.add(splUsrRDTO.getSplId());
				splUsrRMap.put(splUsrRDTO.getUsrId(), splUsrRDTO.getSplId());
			}
			SplInfoQueryCondition splInfoCondition = new SplInfoQueryCondition();
			splInfoCondition.setIds(splIdList);
			splInfoCondition.setIsDel(BaseConstant.IS_YESNO_NO);
			List<SplInfoDTO> splInfoList = this.splInfoApiService.searchSplInfoList(splInfoCondition);
			Map<Long , SplInfoDTO> splInfoMap = new HashMap<Long, SplInfoDTO>();
			for (SplInfoDTO splInfoDTO : splInfoList) {
				splInfoMap.put(splInfoDTO.getId(), splInfoDTO);
			}
			
			// 再次查询登陆时间或准入时间
			Map<Long, Date> reLoginMap = new HashMap<Long, Date>();
			Map<Long, Date> reAccessMap = new HashMap<Long, Date>();
			if (StringUtils.isNotEmpty(loginTmStar) && StringUtils.isNotEmpty(loginTmEnd)) {
				SplActivityRecQC recQC = new SplActivityRecQC();
				recQC.setActivityTypCd("WAL012");
				recQC.setUsrIdList(newUsrIdList);
				recQC.setIsDel(BaseConstant.IS_YESNO_NO);
				recQC.setIsValid(BaseConstant.IS_YESNO_YES);
				List<SplActivityRecVO> searchList = this.splActivityRecService.searchList(recQC);
				if (CollectionUtils.isNotEmpty(searchList)) {
					for (SplActivityRecVO splActivityRecVO : searchList) {
						reAccessMap.put(splActivityRecVO.getUsrId(), splActivityRecVO.getCrtTm());
					}
				}
			}
			if (StringUtils.isNotEmpty(accessTmStar) && StringUtils.isNotEmpty(accessTmEnd)) {
				SplActivityRecQC recQC = new SplActivityRecQC();
				recQC.setActivityTypCd("WAL011");
				recQC.setUsrIdList(newUsrIdList);
				recQC.setIsDel(BaseConstant.IS_YESNO_NO);
				List<SplActivityRecVO> searchList = this.splActivityRecService.searchList(recQC);
				if (CollectionUtils.isNotEmpty(searchList)) {
					for (SplActivityRecVO splActivityRecVO : searchList) {
						reLoginMap.put(splActivityRecVO.getUsrId(), splActivityRecVO.getCrtTm());
					}
				}
			}
			
			for (SplActivityRecVO splActivityRecVO : voList) {
				JSONObject jsonObject = new JSONObject();
				SysUsrDTO oldUsrDTO = oldUsrMap.get(splActivityRecVO.getRenewId());// 推荐人
				SysUsrDTO newUsrDTO = newUsrMap.get(splActivityRecVO.getUsrId());// 被推荐人
				Long splId = splUsrRMap.get(splActivityRecVO.getRenewId());// 推荐人所属经销商ID
				SplInfoDTO splInfoDTO = splInfoMap.get(splId);// 推荐人所属经销商
				
				jsonObject.put("activityTypCd", splActivityRecVO.getActivityTypCd());// 活动类型CODE
				jsonObject.put("oldUsrId", oldUsrDTO.getId());// 推荐人ID
				jsonObject.put("oldUsrNm", oldUsrDTO.getRefRlNm());// 推荐人名称
				jsonObject.put("oldUsrMp", oldUsrDTO.getMp());// 推荐人手机号
				jsonObject.put("oldUsrSplId", splId);// 推荐人所属经销商ID
				if (null != splInfoDTO) {
					jsonObject.put("oldUsrSplNm", splInfoDTO.getSplNm());// 推荐人所属经销商名称
				}
				jsonObject.put("newUsrId", newUsrDTO.getId());// 被推荐人ID
				jsonObject.put("newUsrNm", newUsrDTO.getRefRlNm());// 被推荐人名称
				jsonObject.put("newUsrMp", newUsrDTO.getMp());// 被推荐人手机号
				jsonObject.put("isAccess", isAccessMap.get(splActivityRecVO.getUsrId()));// 被推荐人是否准入
				if (StringUtils.isNotEmpty(loginTmStar) && StringUtils.isNotEmpty(loginTmEnd)) {
					jsonObject.put("isAccess", null == reAccessMap.get(splActivityRecVO.getUsrId()) ? 0 : 1);// 被推荐人准入时间
				}
				jsonObject.put("firstLoginTm", loginTmMap.get(splActivityRecVO.getUsrId()));// 被推荐人首次登陆时间
				if (StringUtils.isNotEmpty(accessTmStar) && StringUtils.isNotEmpty(accessTmEnd)) {
					jsonObject.put("firstLoginTm", reLoginMap.get(splActivityRecVO.getUsrId()));// 被推荐人首次登陆时间
				}
				jsonObject.put("accessTm", accessTmMap.get(splActivityRecVO.getUsrId()));// 被推荐人准入时间
				if (StringUtils.isNotEmpty(loginTmStar) && StringUtils.isNotEmpty(loginTmEnd)) {
					jsonObject.put("accessTm", reAccessMap.get(splActivityRecVO.getUsrId()));// 被推荐人准入时间
				}
				
				resultList.add(jsonObject);
			}
		}
		
		ListPageVO<JSONObject> listPage = new ListPageVO<JSONObject>(resultList, pager.getTotalCount());
		BaseLogUtils.newWebLogger("查询数据完成. DATA:" + JSONObject.toJSONString(page))
				.setLogOperType(LogOperEnum.RESP)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
				.setWarning(false)
				.info();
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.splActivityRecService.removeById(Long.valueOf(id));
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		
		try {
			SplActivityRecVO vo = this.splActivityRecService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
			}
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		SplActivityRecVO entity = null;
		try {
			entity = new SplActivityRecVO();
			//TODO ADD PARAM
			Long id = this.splActivityRecService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		SplActivityRecVO entity = null;
		try {
			entity = new SplActivityRecVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.splActivityRecService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}
		return result;
	}
}

